package trie

// Node 藏词替换
type Node struct {
	children map[rune]*Node
	isEnd    bool
}

type Trie struct {
	root *Node
}

func NewTrie() *Trie {
	return &Trie{
		root: &Node{
			children: make(map[rune]*Node),
		},
	}
}

func (t *Trie) Insert(word string) {
	node := t.root
	for _, ch := range word {
		if _, ok := node.children[ch]; !ok {
			node.children[ch] = &Node{
				children: make(map[rune]*Node),
			}
		}
		node = node.children[ch]
	}
	node.isEnd = true
}

func (t *Trie) Search(word string) bool {
	node := t.root
	for _, ch := range word {
		if _, ok := node.children[ch]; !ok {
			return false
		}
	}
	return node.isEnd
}
func FilterDirtyWords(text string, trie *Trie, replacement rune) string {
	result := []rune(text)
	n := len(result)
	i := 0
	for i < n {
		node := trie.root
		start := i
		for i < n && node.children[result[i]] != nil {
			node = node.children[result[i]]
			i++
			if node.isEnd {
				for j := start; j < i; j++ {
					result[j] = replacement
				}
				break
			}
		}

		if node.isEnd {
			i = start
		} else {
			i++
		}
	}
	return string(result)
}
